<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- 搜索表单保持不变 -->
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="勋章ID" prop="medalId">
        <el-input
          v-model="queryParams.medalId"
          placeholder="请输入勋章ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="勋章名称" prop="medalName">
        <el-input
          v-model="queryParams.medalName"
          placeholder="请输入勋章名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="获得时间" prop="createdTime">
        <el-date-picker clearable
          v-model="queryParams.createdTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择获得时间">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:usermedal:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:usermedal:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:usermedal:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:usermedal:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> -->

    <el-table 
      v-loading="loading" 
      :data="groupedMedalList" 
      @selection-change="handleSelectionChange"
      row-key="userId"
      :default-expand-all="false"
      ref="medalTable"
    >
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-table :data="scope.row.history" border style="width: 95%; margin: 0 auto;">
            <el-table-column label="勋章ID" prop="medalId" align="center"/>
            <el-table-column label="勋章名称" prop="medalName" align="center"/>
            <el-table-column label="获得时间" align="center">
              <template slot-scope="{ row }">
                {{ parseTime(row.createdTime, '{y}-{m}-{d}') }}
              </template>
            </el-table-column>

          </el-table>
        </template>
      </el-table-column>

      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="最新勋章" align="center">
        <template slot-scope="scope">
          <div style="display: flex; align-items: center; justify-content: center">
            <el-image 
              v-if="scope.row.latest.medalImage"
              style="width: 40px; height: 40px; margin-right: 10px"
              :src="scope.row.latest.medalImage" 
              fit="contain"
            ></el-image>
            <span>{{ scope.row.latest.medalName }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="获得时间" align="center" prop="createdTime">
        <template slot-scope="scope">
          {{ parseTime(scope.row.latest.createdTime, '{y}-{m}-{d}') }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="100">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="toggleExpand(scope.row)"
            :icon="scope.row.expanded ? 'el-icon-arrow-down' : 'el-icon-arrow-right'"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户勋章对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="勋章ID" prop="medalId">
          <el-input v-model="form.medalId" placeholder="请输入勋章ID" />
        </el-form-item>
        <el-form-item label="勋章名称" prop="medalName">
          <el-input v-model="form.medalName" placeholder="请输入勋章名称" />
        </el-form-item>
        <el-form-item label="勋章描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="获得时间" prop="createdTime">
          <el-date-picker clearable
            v-model="form.createdTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择获得时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUsermedal, getUsermedal, delUsermedal, addUsermedal, updateUsermedal } from "@/api/system/usermedal";

export default {
  name: "Usermedal",
  data() {
    return {
      groupedMedalList: [],
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        medalId: null,
        medalName: null,
        description: null,
        createdTime: null
      },
      form: {},
      rules: {
        userId: [{ required: true, message: "用户ID不能为空", trigger: "blur" }],
        medalId: [{ required: true, message: "勋章ID不能为空", trigger: "blur" }],
        medalName: [{ required: true, message: "勋章名称不能为空", trigger: "blur" }],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      listUsermedal(this.queryParams).then(response => {
        this.processMedalData(response.rows);
        this.total = response.total; // 保持分页总数正确
        this.loading = false;
      });
    },
    processMedalData(data) {
      const groups = {};
      data.forEach(item => {
        if (!groups[item.userId]) {
          groups[item.userId] = {
            userId: item.userId,
            latest: null,
            history: [],
            expanded: false
          };
        }
        groups[item.userId].history.push(item);
      });

      this.groupedMedalList = Object.values(groups).map(group => {
        // 按时间降序排序，最新在最前
        group.history.sort((a, b) => new Date(b.createdTime) - new Date(a.createdTime));
        group.latest = group.history.shift(); // 取出最新勋章作为单独字段
        return group;
      });
    },
    toggleExpand(row) {
      row.expanded = !row.expanded;
      this.$nextTick(() => {
        const table = this.$refs.medalTable;
        table.toggleRowExpansion(row, row.expanded);
      });
    },
    // 以下为原有功能方法，保持不变
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        userId: null,
        medalId: null,
        medalName: null,
        description: null,
        createdTime: null
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户勋章";
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getUsermedal(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户勋章";
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUsermedal(this.form).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUsermedal(this.form).then(() => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm(`是否确认删除用户勋章编号为"${ids}"的数据项？`).then(() => {
        delUsermedal(ids).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        });
      });
    },
    handleExport() {
      this.download('system/usermedal/export', this.queryParams, `usermedal_${new Date().getTime()}.xlsx`);
    },
    // 时间格式化函数（需要确保在项目中存在，或从公共方法引入）
    parseTime(time, cFormat) {
      if (!time) return "";
      const format = cFormat || "{y}-{m}-{d}";
      const date = time instanceof Date ? time : new Date(time);
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds()
      };
      return format.replace(/{(y|m|d|h|i|s)+}/g, (match, p) => {
        let value = formatObj[p];
        if (p === "m" || p === "d" || p === "h" || p === "i" || p === "s") {
          value = value.toString().padStart(2, "0");
        }
        return value;
      });
    }
  }
};
</script>

<style scoped>
/* 添加箭头旋转动画 */
.el-icon-arrow-down {
  transition: transform 0.3s ease;
}
.el-table__expand-icon.is-expanded .el-icon-arrow-down {
  transform: rotate(180deg);
}
</style>